<?php
// +----------------------------------------------------------------------
// | FastXCMS [ WE CAN DO IT MORE SIMPLE ]
// +----------------------------------------------------------------------
// | Copyright (c) 2013-2018 http://www.fastxcms.com All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +---------------------------------------------------------------------
// | Author: 小夏 < 449134904@qq.com>
// +----------------------------------------------------------------------
namespace cmf\controller;

use think\Db;
use app\portal\service\AdminBaseService;
use app\portal\service\AdminCacheService;

class AdminBaseController extends BaseController
{

    public function _initialize()
    {
        // 监听admin_init
        hook('admin_init');
        parent::_initialize();
		
		// 全局基本公用类
		global $adminBaseService,$adminCacheService;
		$adminBaseService = $this->adminBaseService = new AdminBaseService();
		$adminCacheService = $this->adminCacheService = new AdminCacheService();
		
		// 后台sessionid信息
		$session_admin_id = session('ADMIN_ID');
		
		// 【模块参数程序安装】配置商家扩展功能引入文件（可选）
		$modulehook = "expsupplier";$hookblock = "memberloginsupplier";require(PLUGINS_PATH . 'modulepara/config/modulehook.php');// 商家登录后台 会员登录后访问直接登录供应商后台
		
        if (!empty($session_admin_id)) {
            $user = Db::name('user')->where(['id' => $session_admin_id])->find();

            if (!$this->checkAccess($session_admin_id)) {
                $this->error("您没有访问权限！");
            }			
            $this->assign("admin", $user);
        } else {
			$adminSettings = cmf_get_option('admin_settings');
			if($this->request->module() == "admin") {
				$adminloginurl = "admin/public/login";	
			}else{
				$adminloginurl = "supplier/public/login";
			}
            if ($this->request->isPost()) {
                $this->error("您还没有登录！", url($adminloginurl));
            } else {
                header("Location:" . url($adminloginurl));
                exit();
            }
        }

		// 初始化安装模块参数
		global $configinfo;
		$configinfo['installmodule'] = "default";
		
		if($hook_supplierexpok == 1)
		{
			// 后台模块参数商家程序安装
			$configinfo['adminsuppliermodule'] = 1;
		}
		
		// 目前支持：frontend/admin/supplier
		$modulepara = 'admin';require(PLUGINS_PATH . 'modulepara/config/modulepara.php');	
    }
	// 配置后台模板加载钩子
	public function configadminhook($hookmodule,$hookname,$hookpara="")
	{
		global $lang;
		global $_MGPC_POST,$_MGPC_GET,$_MGPC_REQ,$_MGPC_COOKIE,$_MGPC_SESSION,$configlang,$configinfo,$configblock,$configcommon,$configmember,$configbase,$configsystem,$configindex,$configother;
		
		// 文章模块时调用钩子
		if($this->request->module() == "portal")
		{
			if($hookmodule)
			{
				$path = MODULEPARA_PATH;
				$tplpath = "../../../plugins/modulepara/";
				if(iffile($path . 'config/hook/hook_'.$hookmodule.'/'.$hookname.'.php') == 1)
				{
					if(iffile($path . 'config/hook/hook_'.$hookmodule.'/hookconfig.php') == 1)
					{
						require($path . 'config/hook/hook_'.$hookmodule.'/hookconfig.php');
					}
					require($path . 'config/hook/hook_'.$hookmodule.'/'.$hookname.'.php');
					if(empty($datacontent))$datacontent = $this->fetch($tplpath . 'config/hook/hook_'.$hookmodule . '/tpl/' . $hookname);
				}
				
				// 加载模板程序配置
				if($configinfo['tplok'] == 1)
				{
					$path = $configinfo['tplurl'];
					$tplpath = "../../".$configinfo['tplname']."/model/";
					if(iffile($path . 'config/hook/hook_'.$hookmodule.'/'.$hookname.'.php') == 1)
					{
						if(iffile($path . 'config/hook/hook_'.$hookmodule.'/hookconfig.php') == 1)
						{
							require($path . 'config/hook/hook_'.$hookmodule.'/hookconfig.php');
						}
						require($path . 'config/hook/hook_'.$hookmodule.'/'.$hookname.'.php');
						if(empty($tpldatacontent))$tpldatacontent = $this->fetch($tplpath . 'config/hook/hook_'.$hookmodule . '/tpl/' . $hookname);
						$datacontent = gettpldata($datacontent,$tpldatacontent);
					}
				}
				
				// 公用模块参数配置不同模块数据
				if($hookmodule == 'configmodulepara')
				{
					require(MODULEPARA_PATH . 'config/hook/hook_'.$hookmodule.'/hookmodule.php');	
				}
				
				$this->assign($hookname, $datacontent);

				return $datacontent;
			}
		}
	}
	public function smarty_assign($varname,$var)
	{		
		$this->assign($varname, $var);		
	}

    public function _initializeView()
    {
        $cmfAdminThemePath    = config('cmf_admin_theme_path');
        $cmfAdminDefaultTheme = cmf_get_current_admin_theme();

        $themePath = "{$cmfAdminThemePath}{$cmfAdminDefaultTheme}";

        $root = cmf_get_root();

        //使cdn设置生效
        $cdnSettings = cmf_get_option('cdn_settings');
        if (empty($cdnSettings['cdn_static_root'])) {
            $viewReplaceStr = [
                '__ROOT__'     => $root,
                '__TMPL__'     => "{$root}/{$themePath}",
                '__STATIC__'   => "{$root}/static",
                '__WEB_ROOT__' => $root
            ];
        } else {
            $cdnStaticRoot  = rtrim($cdnSettings['cdn_static_root'], '/');
            $viewReplaceStr = [
                '__ROOT__'     => $root,
                '__TMPL__'     => "{$cdnStaticRoot}/{$themePath}",
                '__STATIC__'   => "{$cdnStaticRoot}/static",
                '__WEB_ROOT__' => $cdnStaticRoot
            ];
        }

        $viewReplaceStr = array_merge(config('view_replace_str'), $viewReplaceStr);
        config('template.view_base', "$themePath/");
        config('view_replace_str', $viewReplaceStr);
    }

    /**
     * 初始化后台菜单
     */
    public function initMenu()
    {
    }

    /**
     *  检查后台用户访问权限
     * @param int $userId 后台用户id
     * @return boolean 检查通过返回true
     */
    private function checkAccess($userId)
    {
        // 如果用户id是1，则无需判断
        if ($userId == 1) {
            return true;
        }

        $module     = $this->request->module();
        $controller = $this->request->controller();
        $action     = $this->request->action();
        $rule       = $module . $controller . $action;

        $notRequire = ["adminIndexindex", "adminMainindex"];
        if (!in_array($rule, $notRequire)) {
            return cmf_auth_check($userId);
        } else {
            return true;
        }
    }

}